<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="queryParams.tableName" placeholder="表名称" class="filter-item search-item" />
      <el-input v-model="queryParams.tableComment" placeholder="表描述" class="filter-item search-item" />
      <el-date-picker
        style="display: inline-block;vertical-align:middle;margin-bottom: 10px;margin-right: 10px"
        v-model="queryParams.timeRange"
        type="daterange"
        range-separator=""
        value-format="yyyy-MM-dd HH:mm:ss "
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>

      <el-button class="filter-item" type="primary" @click="search">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" type="success" @click="reset">
        {{ $t('table.reset') }}
      </el-button>

      <el-dropdown trigger="click" class="filter-item">
        <el-button>
          {{ $t('table.more') }}<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="add">{{ "导入" }}</el-dropdown-item>
          <el-dropdown-item @click.native="batchCode">{{ "生成" }}</el-dropdown-item>
          <el-dropdown-item @click.native="batchDelete">{{ "删除" }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-table
      ref="table"
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      style="width: 100%;"
      @selection-change="onSelectChange"
    >
      <el-table-column type="selection" align="center" width="40px" />
      <el-table-column label="表名称" prop="tableName" :show-overflow-tooltip="true" align="center" min-width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.tableName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="表描述" prop="tableComment" :show-overflow-tooltip="true" align="center" min-width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.tableComment}}</span>
        </template>
      </el-table-column>
      <el-table-column label="实体" prop="className" :show-overflow-tooltip="true" align="center" min-width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.className }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" :show-overflow-tooltip="true" align="center" min-width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updateTime" :show-overflow-tooltip="true" align="center" min-width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.operation')" align="center" min-width="150px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <i class="el-icon-view table-operation" style="color: #87d068;" @click="previewCode(row)" />
          <i  class="el-icon-setting table-operation" style="color: #2db7f5;" @click="edit(row)" />
          <i  class="el-icon-delete table-operation" style="color: #f50;" @click="singleDelete(row)" />
          <i class="el-icon-refresh table-operation" style="color: #ffa856;" @click="sync(row)" />
          <i  class="el-icon-download table-operation" style="color: #2db7f5;" @click="downLoad(row)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="pagination.num" :limit.sync="pagination.size" @pagination="search" />

    <import-table
      ref="table1"
      :dialog-visible="dialog.isVisible"
      @success="editSuccess"
      @close="editClose"
    />

    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :key="key"
        >
          <el-link :underline="false" icon="el-icon-document-copy" @click="copyCode($event,value)" style="float:right">复制</el-link>
          <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
  import {
    genTablePage,
    genTableDelete,
    customCode,
    downloadCodeZip,
    syncDb,
    genTablePreview
  } from '@/api/gen/gen'
  import importTable from '@/views/xy/gen/generate2/components/importTable'
  import Pagination from '@/components/Pagination'
  import hljs from "highlight.js/lib/highlight";
  import "highlight.js/styles/github-gist.css";
  // 导入复制文字的功能
  import handleClipboard from "@/utils/clipboard.js";
  hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
  hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
  hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
  hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
  hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
  hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
  export default {
    name: "index2",
    components: { Pagination ,importTable},
    data() {
      return {
        tableKey: 0,
        loading: false,
        list: [],
        total: 0,
        queryParams: {},
        selection: [],
        pagination: {
          size: 10,
          num: 1
        },
        dialog:{
          isVisible:false
        },
        // 预览参数
        preview: {
          open: false,
          title: "代码预览",
          data: {},
          activeName: "entity.java"
        }
      }
    },
    mounted() {
      this.fetch()
    },
    activated(){
      console.log("acti查询")
      this.fetch()
    },
    methods: {
      copyCode($event,value){
        console.log("复制")
        handleClipboard(value, $event);
      },
      /** 高亮显示 */
      highlightedCode(code, key) {
        const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
        let language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
        const result = hljs.highlight(language, code || "", true);
        return result.value || '&nbsp;';
      },
      search(){
        this.fetch({
          ...this.queryParams,
          ...this.sort
        })
      },
      fetch(params = {}){
        params.pageSize = this.pagination.size
        params.pageNum = this.pagination.num
        if (this.queryParams.timeRange) {
          params.beginTime = this.queryParams.timeRange[0]
          params.endTime = this.queryParams.timeRange[1]
        }
        this.loading = true
        genTablePage(params).then(res=>{
          if(res.code==200){
            this.total = res.data.total
            this.list = res.data.rows
          }
        }).finally(final=>{
          this.loading = false
        })
      },
      reset(){
        this.queryParams = {}
        this.sort = {}
        this.$refs.table.clearSort()
        this.$refs.table.clearFilter()
        this.search()
      },
      add(){
        this.dialog.isVisible = true
      },
      singleDelete(row){
        this.$refs.table.toggleRowSelection(row, true)
        this.batchDelete()
      },
      batchDelete(){
        if (!this.selection.length) {
          this.$message({
            message: this.$t('tips.noDataSelected'),
            type: 'warning'
          })
          return
        }
        this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          const tableId = []
          this.selection.forEach((u) => {
            tableId.push(u.tableId)
          })
            this.delete(tableId)
        }).catch(() => {
          this.clearSelections()
        })
      },
      clearSelections() {
        this.$refs.table.clearSelection()
      },
      delete(tableIds) {
        this.loading = true
        genTableDelete(tableIds.join(",")).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.deleteSuccess'),
              type: 'success'
            })
            this.search()
          }
        }).finally(final=>{
          this.loading = false
        })
      },
      batchCode(){
        if (!this.selection.length) {
          this.$message({
            message: this.$t('tips.noDataSelected'),
            type: 'warning'
          })
          return
        }
        downloadCodeZip(this.selection.map(t=>{ return t.tableName}).join(","),"code.zip")
      },
      onSelectChange(selection){
        this.selection = selection
      },
      editSuccess(){
        this.search()
        this.dialog.isVisible = false
      },
      downLoad(row){
        if(row.genType === "1") {
          customCode(row.tableName).then(res=>{
            if(res.code==200){
              this.$message({
                message: "成功生成到自定义路径：" + row.genPath,
                type: 'success'
              })
            }
          })
        } else {
          downloadCodeZip(row.tableName,row.tableName+"code.zip")
        }
      },
      sync(row){
        this.$confirm("选中数据将被还原, 是否继续？", this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          syncDb(row.tableName).then(res=>{
            if(res.code==200){
              this.search()
              this.$message({
                message: "同步成功",
                type: 'success'
              })
            }
          })
        })
      },
      editClose(){
        this.dialog.isVisible = false
      },
      previewCode(row){
        genTablePreview(row.tableId).then(res=>{
          if(res.code==200){
            this.preview.data = res.data;
            this.preview.open = true;
            this.preview.activeName = "entity.java";
          }else {
            this.$message({
              message: res.data.message,
              type: 'error'
            })
          }
        })
      },
      edit(row){
        this.$router.push({
          name: 'genDetailIndex',
          query: {
            tableId:row.tableId
          },
        })
      }
    }
  }
</script>

<style scoped>

</style>
